package com.kehutong.scheduled.util;

import org.coraframework.inject.Singleton;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.threadpool.ThreadPool;
import org.coraframework.util.Ioc;
import org.coraframework.util.Queue;

import com.kehutong.common.worker.Worker;


@Singleton
public class ScheduledTasker extends Thread {
	
	private static final Logger logger = LoggerFactory.getLogger(ScheduledTasker.class);
	
	private static ScheduledTasker taskQueue = new ScheduledTasker();;
	
	public static ScheduledTasker getInstance() {
		return taskQueue;
	}
	
	private ScheduledTasker() {
		isFlag = false;
		queue = new Queue<>();
		setDaemon(true);
		this.threadPool = Ioc.getInstance(ThreadPool.class);
		this.startUP();
	}
	
	private boolean isFlag;
	private Queue<Worker<?>> queue;
	private ThreadPool threadPool;

	
	public boolean addWork(Worker<?> run) {
		logger.info("queue task count={}", queue.size());
		synchronized (this) {
			queue.push(run);
			this.notify();
		}
		return true;
	}
	
	
	public void startUP() {
		isFlag = false;
		this.start();
	}
	
	public void shutDown() {
		isFlag = true;
	}
	
	@Override
	public void run() {
		while (!isFlag) {
			synchronized (this) {
				try {
					this.wait(60000L);
				} catch (InterruptedException e) {
				}
			}
			
			for (Worker<?> work : queue) {
				try {
					threadPool.execute(work);
				} catch (Exception e) {
					logger.error("", e);
				}
			}
		}
	}
}
